<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>分类列表-懒加载</span>
		</div>
		<el-tree :load="loadNode" lazy ref="tree" node-key="cate_id" :props="defaultProps">
			<!-- 作用域插槽 ；{ node, data }是解构得到，node是节点对象，data是渲染的数据对象-->
			<span class="custom-tree-node" slot-scope="{ node, data }">
				<span>{{ node.label }}</span>
				<span>
					<!-- .stop阻止事件冒泡 ，防止点击时自动展开-->
					<el-button v-permission="'category:edit'" type="text" icon="el-icon-edit"
						@click.stop="openEditDialog(node, data)" :disabled="data.cate_id === 0">编辑</el-button>
					<el-button v-permission="'category:create'" type="text" icon="el-icon-circle-plus-outline"
						@click.stop="openInsertDialog(node, data)">
						添加
					</el-button>
					<el-button v-permission="'category:remove'" type="text" icon="el-icon-delete"
						@click.stop="handleRemove(node, data)" :disabled="data.cate_id === 0">删除
					</el-button>
				</span>
			</span>
		</el-tree>

		<!-- 添加分类 -->
		<el-dialog title="添加分类" :visible.sync="insert_dialog_visible" @close="handleCloseDialog('insert_form')">
			<el-form :model="insert_form" ref="insert_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="分类名称:" prop="cate_name">
					<el-input type="text" v-model="insert_form.cate_name" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="insert_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleInsert">添加</el-button>
			</span>
		</el-dialog>

		<!-- 编辑分类 -->
		<el-dialog title="编辑分类" :visible.sync="edit_dialog_visible" @close="handleCloseDialog('edit_form')">
			<el-form :model="edit_form" ref="edit_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="分类名称:" prop="cate_name">
					<el-input type="text" v-model="edit_form.cate_name" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="edit_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleEdit">保存</el-button>
			</span>
		</el-dialog>
	</el-card>
</template>

<script>
import { Category } from "@/api";
import axios from "axios";
export default {
	name: 'List',
	data() {
		return {
			data: [],
			defaultProps: {
				/* 根据返回的数据 */
				children: 'children',
				label: 'cate_name',
			},
			insert_dialog_visible: false,
			insert_form: {
				cate_name: '',
				parent_id: '',
			},
			rules: {
				cate_name: [{ required: true, message: "请填写分类名称！", trigger: 'blur' }]
			},
			// 当前操作的 node
			current_node: '',
			edit_dialog_visible: false,
			edit_form: {
				cate_name: '',
				parent_id: '',
			},
		};
	},
	methods: {
		// 加载子级分类
		async loadNode(node, resolve) {
			// console.log(node, resolve);
			// 根节点
			let root_data = [{
				cate_id: 0,
				cate_name: "全部分类",
			}];
			if (node.level === 0) {
				return resolve(root_data);
			}
			// 子级节点
			let { cate_id } = node.data;
			let { status, msg, data } = await Category.sub({ cate_id });
			if (status) {
				// 生成子级节点
				resolve(data);
			}
		},
		// 关闭弹窗，清除表单验证状态
		handleCloseDialog(formName) {
			// formName是变量，不能使用 ref.formName
			this.$refs[formName].resetFields();
		},
		// 打开添加分类弹窗
		openInsertDialog(node, data) {
			// 缓存当前操作的 node
			this.current_node = node;
			// 转存parent_id
			this.insert_form.parent_id = data.cate_id;
			this.insert_dialog_visible = true;
		},
		// 添加分类
		handleInsert() {
			this.$refs.insert_form.validate(async (valid) => {
				if (valid) {
					let { status, msg, data } = await Category.add({ ...this.insert_form });
					if (status) {
						// 操作DOM：懒加载无法得到全部数据
						let new_child = { ...this.insert_form, ...data };
						this.$refs.tree.append(new_child, this.current_node);
						// 关闭弹窗
						this.insert_dialog_visible = false;
						// 信息提示
						this.$message.success(msg);
					} else {
						this.$message.error(msg);
					}
				}
			});
		},
		// 打开编辑弹窗
		openEditDialog(node, data) {
			// 缓存当前操作的 node
			this.current_node = node;
			// 还原表单
			this.edit_form = { ...data };
			this.edit_dialog_visible = true;
		},
		// 编辑分类
		handleEdit() {
			// 表单验证
			this.$refs.edit_form.validate(async (valid) => {
				if (valid) {
					let { status, msg } = await Category.edit({ ...this.edit_form });
					if (status) {
						// 操作DOM：让vue知道我们修改了数据，后续vue会自动虚拟DOM、对比等操作，从而实现数据的更新
						this.current_node.data = { ...this.edit_form };
						/* 写法2： Object.assign(this.current_node.data, this.edit_form); */
						// 关闭弹窗
						this.edit_dialog_visible = false;
						// 添加成功信息提示
						this.$message.success(msg);
					} else {
						// 添加失败信息提示
						this.$message.error(msg);
					}
				}
			});
		},
		// 删除分类
		handleRemove(node, data) {
			console.log(node);
			let { cate_id } = data;
			this.$confirm('此操作将永久删除该分类, 是否继续?', '警告', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Category.remove({ cate_id });
					if (status) {
						// 操作 DOM
						this.$refs.tree.remove(data);
						// 信息提示
						this.$message.success(msg);
					} else {
						// 信息提示
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info('已取消删除！');
				});
		}

	},
};
</script>

<style>
.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}
</style>
